/**
 * 
 */
package edu.cmu.cs.webapp.ioms.actions.order;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPart;

import edu.cmu.cs.webapp.ioms.dao.DataAccessException;
import edu.cmu.cs.webapp.ioms.dao.impl.OrderDAOImpl;
import edu.cmu.cs.webapp.ioms.models.PurchaseOrder;
import edu.cmu.cs.webapp.ioms.ui.wizards.order.OrderWizard;
import edu.cmu.cs.webapp.ioms.views.OrdersListView;

/**
 * @author Christian
 * 
 */
public class EditOrderViewAction implements IViewActionDelegate,
		IObjectActionDelegate {
	private PurchaseOrder model;
	private OrdersListView _view;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IViewActionDelegate#init(org.eclipse.ui.IViewPart)
	 */
	@Override
	public void init(IViewPart view) {
		this._view = (OrdersListView) view;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	@Override
	public void run(IAction action) {
		if (this.model != null) {
			OrderWizard wizard = new OrderWizard(true, model);
			wizard.setWindowTitle("Edit Order");
			WizardDialog dialog = new WizardDialog(_view.getViewSite()
					.getShell(), wizard);
			dialog.setBlockOnOpen(true);
			dialog.open();

			int returnCode = dialog.getReturnCode();

			if (returnCode == org.eclipse.jface.window.Window.OK) {
				// edit order
				// create new order
				PurchaseOrder order = wizard.getModel();
				try {
					new OrderDAOImpl().updateOrder(order);
				} catch (DataAccessException e) {
					e.printStackTrace();
				}
			} else {
			}

			this._view.refreshOrdersView();
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action
	 * .IAction, org.eclipse.jface.viewers.ISelection)
	 */
	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		if (selection instanceof IStructuredSelection) {
			Object obj = ((IStructuredSelection) selection).getFirstElement();
			if (obj instanceof PurchaseOrder) {
				this.model = (PurchaseOrder) obj;
			}
		}

	}

	@Override
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		// TODO Auto-generated method stub

	}

}
